package com.aster.base.controller;


import com.aster.base.domain.RoleDO;
import com.aster.base.domain.UserDO;
import com.aster.base.dto.UserDTO;
import com.aster.base.dto.do2dto.UserConvert;
import com.aster.base.service.RoleService;
import com.aster.base.service.UserService;
import com.aster.base.utils.MD5Utils;
import com.aster.common.annotation.Log;
import com.aster.common.constants.CommonConstants;
import com.aster.common.context.FilterContextHandler;
import com.aster.common.dto.LoginUserDTO;
import com.aster.common.dto.UserToken;
import com.aster.common.utils.JwtUtils;
import com.aster.common.utils.PageUtils;
import com.aster.common.utils.Query;
import com.aster.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户信息
 * @author bootdo
 */
@RequestMapping("/user")
@RestController
public class UserController extends BaseController {
    @Autowired
	UserService userService;
    @Autowired
	RoleService roleService;

	/**
	 * 登录的当前用户，前台需要验证用户登录的页面可以调用此方法
	 * @return
	 */
    @GetMapping("/currentUser")
	LoginUserDTO currentUser(){
		LoginUserDTO loginUserDTO = new LoginUserDTO();
		loginUserDTO.setUserId(FilterContextHandler.getUserID());
		loginUserDTO.setUsername(FilterContextHandler.getUsername());
		loginUserDTO.setName(FilterContextHandler.getName());
		return loginUserDTO;
	}

	/**
	 * 根据用户id获取用户
	 * @param id
	 * @return
	 */
    @GetMapping("{id}")
	R get(@PathVariable("id") Long id ){
		UserDTO userDTO = UserConvert.MAPPER.do2dto(userService.get(id));
    	return R.ok().put("data",userDTO);
	}

	/**
	 * 分页查询用户
	 * @param params
	 * @return
	 */
	@Log("获取用户列表")
    @GetMapping
    R listByPage(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<UserDTO> userDTOS = UserConvert.MAPPER.dos2dtos((userService.list(query)));
        List<UserDTO> userDTOList = new ArrayList<>();
		for (UserDTO userDTO:userDTOS ) {
			long userId = userDTO.getUserId();
			List<RoleDO> roles = roleService.rolesByUserId(userId);
			StringBuffer sb = new StringBuffer();
			if (roles != null && roles.size() >0){
				for (RoleDO roleDo:roles ) {
					sb.append(roleDo.getRoleName()).append(",");
				}
				sb.deleteCharAt(sb.length() - 1);
			}
			userDTO.setRoleNames(sb.toString());
			userDTOList.add(userDTO);
		}
        int total = userService.count(query);
        PageUtils pageUtil = new PageUtils(userDTOList, total);
        return R.ok().put("page",pageUtil);
    }

	 /**
	 * 增加用户
	 * @param user
	 * @return
	 */
	@PostMapping
    R save(@RequestBody UserDO user) {
		user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
		return R.operate(userService.save(user) > 0);
	}

	/**
	 * 修改用户
	 * @param user
	 * @return
	 */
	@PutMapping
	R update(@RequestBody UserDO user) {
		return R.operate(userService.update(user) > 0);
	}

	/**
	 * 修改密码
	 * @param user
	 * @param headers
	 * @return
	 */
	@PutMapping("/changePwd")
	R changePassword(@RequestBody UserDTO user, HttpServletRequest headers){
		try {
			String accessToken = headers.getHeader(CommonConstants.CONTEXT_TOKEN);
			UserToken userToken = JwtUtils.getInfoFromToken(accessToken);
			long id = Long.parseLong(userToken.getUserId());
			UserDO userDO = userService.get(id);
			// 旧密码
			String oldPwd = user.getOldPwd();
			// 新密码
			String newPwd = user.getNewPwd();
			// 对比旧密码是否正确
			String md5Psd = MD5Utils.encrypt(userDO.getUsername(), oldPwd);
			if (!md5Psd.equals(userDO.getPassword())){
				return R.error(10001,"原密码不对");
			}
			userDO.setPassword(MD5Utils.encrypt(userDO.getUsername(), newPwd));
			userService.update(userDO);
			return R.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return R.error(10001,e.getMessage());
		}
	}

    /**
     * 修改个人信息
     * @param user
     * @param headers
     * @return
     */
    @PutMapping("/profile")
    R changeProfile(@RequestBody UserDO user, HttpServletRequest headers){
        try {
            String accessToken = headers.getHeader(CommonConstants.CONTEXT_TOKEN);
            UserToken userToken = JwtUtils.getInfoFromToken(accessToken);
            long id = Long.parseLong(userToken.getUserId());
            user.setUserId(id);
            userService.update(user);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(10001,e.getMessage());
        }
    }

	/**
	 * 删除用户
	 * @param id
	 * @return
	 */
	@DeleteMapping
	R remove( Long id) {
		return R.operate (userService.remove(id) > 0);
	}

	/**
	 * 重置密码
	 * @param user
	 * @return
	 */
	@PutMapping("/reset")
	R resetPassword(@RequestBody UserDO user){
		UserDO userDO = new UserDO();
		userDO.setUserId(user.getUserId());
		UserDO userDO1 = userService.get(user.getUserId());
		// 重置密码
		user.setPassword(MD5Utils.encrypt(userDO1.getUsername(), "123456"));
		return R.operate(userService.update(user) > 0);
	}

	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] userIds) {
		int r = userService.batchremove(userIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/exits")
	@ResponseBody
	boolean exits(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return !userService.exits(params);
	}
}
